import React, { PureComponent } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';

import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tabs,
  Table,
  Upload,
  List,
  Avatar,
  Checkbox,
  Tooltip,
} from 'antd';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import StandardTable from '@/components/StandardTable';
import MyIcon from '@/components/MyIcon';
import IconButton from '@/components/IconButton';
import Headline from '@/components/Headline';
import styles from './AppConfig.less';

const FormItem = Form.Item;
const InputGroup = Input.Group;
const Description = DescriptionList.Description;
const { TabPane } = Tabs;

const EXTENSIONS = {
  HO: {
    cargoUser: '用户名',
    agentCode: '代理编码',
    officeCode: '营业点编码',
    officeName: '营业点名称',
    threeLetterCode: '代理人三字码',
    telphone: '电话',
    iataCode: 'iata编码',
    cassCode: 'cass编码',
  },
  OTHER: {
    agentCode: '代理编码',
    officeName: '营业点名称',
    telphone: '电话',
    iataCode: 'iata编码',
    cassCode: 'cass编码',
  },
};

const EXTENSIONS_RULE = {
  cargoUser: {
    required: true,
    pattern: /^[a-zA-Z0-9]+$/,
    message: '请输入字母和数字',
  },
  agentCode: {
    required: true,
    pattern: /^[a-zA-Z\-+*_]+$/,
    message: '请输入字母和符号"-"、"+"、"_"、"*"',
  },
  officeCode: {
    required: true,
    pattern: /^[a-zA-Z\-+*_]+$/,
    message: '请输入字母和符号"-"、"+"、"_"、"*"',
  },
  officeName: {
    required: true,
    message: '请输入营业点名称',
  },
  threeLetterCode: {
    required: false,
    pattern: /^[\s\S]{0,10}$/,
    message: '最多输入10个字符',
  },
  telphone: {
    required: false,
    pattern: /^[0-9\-+*_]+$/,
    message: '请输入数字和符号"-"、"+"、"_"、"*"',
  },
  iataCode: {
    required: false,
    pattern: /^[a-zA-Z]+$/,
    message: '请输入正确得iata编码',
  },
  cassCode: {
    required: false,
    pattern: /^[a-zA-Z0-9]+$/,
    message: '请输入正确得cass编码',
  },
};
let cardStyle = {
  bordered: false,
  headStyle: { border: 'none' },
  style: { width: '100%' },
};

@Form.create()
@connect(({ loading, app }) => ({
  loading: loading.effects['app/queryAppConfigList'],
  actionLoading: loading.effects['app/createAppConfig'] || loading.effects['app/updateAppConfig'],
  appConfigList: app.appConfigList,
}))
class AppConfig extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      type: 'create',
      visible: false,
      bindAppConfig: {},
      selectedRowKeys: [],
      selectedRows: [],
    };
  }

  componentDidMount() {
    this.queryAppConfigList();
  }

  columns = [
    {
      title: formatMessage({ id: 'sysSet.Common.index' }),
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: formatMessage({ id: 'sysSet.FrontApp.FrontApp.appName' }),
      dataIndex: 'appTypeName',
    },

    {
      title: formatMessage({ id: 'sysSet.Common.code' }),
      dataIndex: 'code',
    },
    {
      title: formatMessage({ id: 'sysSet.Common.name' }),
      dataIndex: 'name',
    },
    {
      title: formatMessage({ id: 'sysSet.Common.typeName' }),
      dataIndex: 'typeName',
    },
    {
      title: formatMessage({ id: 'sysSet.Common.protocolTypeName' }),
      dataIndex: 'protocolTypeName',
    },
  ];

  calcIndex = index => {
    const { appConfigList } = this.props;
    let currentPage = get(appConfigList, 'pagination.currentPage') || 1;
    let pageSize = get(appConfigList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  formatConfigExtensions = extensions => {
    const { bindAppConfig } = this.state;
    const config = EXTENSIONS[bindAppConfig.code === 'HO' ? 'HO' : 'OTHER'];
    const obj = Object.create(null);
    try {
      Object.keys(config).forEach(key => {
        const extension = extensions.find(item => item.keyName === key);
        if (extension) {
          obj[key] = extension.keyValue;
        }
      });
    } catch (error) {}
    return obj;
  };

  formatFieldsValue = fieldsValue => {
    const { bindAppConfig } = this.state;
    const {
      location: { query },
    } = this.props;
    let params = [];
    try {
      Object.keys(fieldsValue).forEach(key => {
        const obj = Object.create(null);
        if (bindAppConfig.configs) {
          obj.id = (bindAppConfig.configs.find(config => config.keyName === key) || {}).id;
        }

        obj.keyName = key;
        obj.keyValue = fieldsValue[key];
        obj.thirdAppId = bindAppConfig.id;
        obj.appUserId = query.appUserId;
        params.push(obj);
      });
    } catch (error) {}

    return params;
  };

  queryAppConfigList = ({ pageIndex = 1, pageSize = 50, ...params } = {}) => {
    const {
      dispatch,
      form,
      location: { query },
    } = this.props;
    let payload = {
      pageIndex: pageIndex,
      pageSize: pageSize,
      ...params,
    };
    dispatch({
      type: 'app/queryAppConfigList',
      payload: {
        pathParams: {
          appUserId: query.appUserId,
        },
        queryParams: payload,
      },
    });
  };

  queryAppConfigDetail = thirdAppId => {
    const {
      dispatch,
      form,
      location: { query },
    } = this.props;
    return dispatch({
      type: 'app/queryAppConfigDetail',
      payload: {
        pathParams: {
          thirdAppId,
          appUserId: query.appUserId,
        },
      },
    });
  };

  createAppConfig = params => {
    return this.props.dispatch({
      type: 'app/createAppConfig',
      payload: {
        data: this.formatFieldsValue(params),
      },
    });
  };

  updateAppConfig = params => {
    return this.props.dispatch({
      type: 'app/updateAppConfig',
      payload: {
        data: this.formatFieldsValue(params),
      },
    });
  };

  unbindAppConfig = () => {
    return this.props.dispatch({
      type: 'app/unbindAppConfig',
      payload: {
        pathParams: {
          appUserId: this.props.location.query.appUserId,
        },
        data: this.state.selectedRows.map(row => row.id),
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.queryAppConfigList(params);
  };

  handleModalOnOk = () => {
    const { form } = this.props;
    form.validateFields(async (err, values) => {
      if (err) {
        return;
      }
      const res = await (this.state.type === 'create'
        ? this.createAppConfig(values)
        : this.updateAppConfig(values));
      if (res.errorCode === 0) {
        message.success(formatMessage({ id: 'sysSet.Common.bindSuccess' }));
        this.queryAppConfigList();
        this.setState({
          visible: false,
          selectedRows: [],
          selectedRowKeys: [],
        });
      }
    });
  };

  handleModalOnCancle = () => {
    this.setState({
      visible: false,
    });
  };

  handleCreateClick = async () => {
    this.props.form.resetFields();
    this.setState({
      type: 'create',
      visible: true,
    });
  };

  handleEditClick = async id => {
    const {
      form: { setFieldsValue, resetFields },
    } = this.props;
    this.setState({
      type: 'edit',
      visible: true,
    });
    const res = await this.queryAppConfigDetail(id);
    if (res.errorCode === 0) {
      setFieldsValue(this.formatConfigExtensions(res.data));
    }
  };

  handleBindClick = () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length !== 1) {
      return;
    }
    const {
      selectedRows: [selectedRow],
    } = this.state;
    // if (!EXTENSIONS[selectedRow.code]) {
    //   message.info('无相关绑定配置');
    //   return;
    // }
    this.setState({
      bindAppConfig: selectedRow,
    });
    if (selectedRow.configs) {
      this.handleEditClick(selectedRow.id);
    } else {
      this.handleCreateClick();
    }
  };

  handleUnbindClick = () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length < 1) {
      return;
    }
    Modal.confirm({
      title: formatMessage({ id: 'sysSet.FrontApp.AppConfig.unbind' }),
      content: formatMessage({ id: 'sysSet.FrontApp.AppConfig.sureToUnbind' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.unbindAppConfig();
        if (res.errorCode === 0) {
          this.setState({
            selectedRowKeys: [],
          });
          this.queryAppConfigList();
          message.success(formatMessage({ id: 'sysSet.FrontApp.AppConfig.unbindSuccess' }));
        }
      },
    });
  };

  handleSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  renderModal = () => {
    const { visible, bindAppConfig } = this.state;
    const {
      actionLoading,
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    const extensions = EXTENSIONS[bindAppConfig.code === 'HO' ? 'HO' : 'OTHER'] || {};
    return (
      <Modal
        confirmLoading={actionLoading}
        maskClosable={false}
        keyboard={false}
        destroyOnClose
        title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.bindConfig' })}
        visible={visible}
        onOk={this.handleModalOnOk}
        onCancel={this.handleModalOnCancle}
      >
        <Form layout="horizontal" {...formItemLayout} labelAlign="right">
          {Object.keys(extensions).map(key => {
            return (
              <FormItem label={extensions[key]} key={key}>
                {getFieldDecorator(key, {
                  normalize: value => {
                    return value && value.replace(/\s/g, '');
                  },
                  rules: [
                    {
                      pattern: /^[\s\S]{0,64}$/,
                      message: formatMessage({ id: 'common.limitLengthTip' }, { limit: 64 }),
                    },
                    {
                      ...EXTENSIONS_RULE[key],
                    },
                  ],
                })(
                  <Input
                    // maxLength={64}
                    placeholder={`请输入${extensions[key]}`}
                  />
                )}
              </FormItem>
            );
          })}
        </Form>
      </Modal>
    );
  };

  renderTable = () => {
    const { loading, appConfigList } = this.props;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleSelectChange,
    };
    return (
      <StandardTable
        showCheckbox
        selectedRows={selectedRowKeys}
        rowSelection={rowSelection}
        rowKey="id"
        loading={loading}
        data={appConfigList}
        columns={this.columns}
        onChange={this.handleStandardTableChange}
      />
    );
  };

  render() {
    const { location } = this.props;
    return (
      <React.Fragment>
        <Headline
          style={{ marginBottom: 20 }}
          title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.bindConfig' })}
          backRoute={`/system/edi/frontApp/appConfig/bind?appId=${location.query.appId}`}
        />
        <Card {...cardStyle} className={styles.cargoApply}>
          <div style={{ marginBottom: 20, height: '30px' }}>
            {
              <div>
                <IconButton
                  title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.bindConfig' })}
                  icon="iconoss---bangding"
                  onClick={this.handleBindClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.FrontApp.AppConfig.unbind' })}
                  icon="iconoss---jiechubangding"
                  onClick={this.handleUnbindClick}
                />
              </div>
            }
          </div>
          {this.renderTable()}
          {this.renderModal()}
        </Card>
      </React.Fragment>
    );
  }
}

export default AppConfig;
